﻿package org.leles.utils 
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
	
	/**
	 * ...
	 * @author Bruno leles
	 */
	public class OpenURL
	{
		/**
		 * 
		 * @param	object
		 * @param	url
		 * @param	window
		 * @param	event
		 * @return
		 */
		public static function create( object:EventDispatcher, url:Object, window:String = "_blank", event:String = "click" ):OpenURL
		{
			return new OpenURL( object, url, window, event );
		}
		
		protected var object:EventDispatcher;
		protected var request:URLRequest;
		protected var window:String;
		protected var event:String;
		
		/**
		 * 
		 * @param	object
		 * @param	url
		 * @param	window
		 * @param	event
		 */
		public function OpenURL( object:EventDispatcher, url:Object, window:String = "_blank", event:String = "click" ) 
		{
			if ( url is String ) this.request = new URLRequest( url as String );
			else
			if ( url is URLRequest ) this.request = url as URLRequest;
			else throw new Error("URL must be a String or a URLRequest object");
			
			this.window = window;
			this.object = object;
			this.event = event;
			
			startHandle();
		}
		
		/**
		 * add the listener in the object
		 */
		public function startHandle():void		{ object.addEventListener( event , _eventCallback ); }
		
		/**
		 * removes the listener from the object
		 */
		public function stopHandle():void		{ object.removeEventListener( event , _eventCallback ); }
		
		protected function _eventCallback(e:Event):void {navigateToURL( request, window );}
	}
	
}